const express = require('express');
const expressWs = require('express-ws');

const app = express();
expressWs(app);

// 存储连接的客户端
const clients = new Set();

// 处理 WebSocket 请求
app.ws('/chat', (ws, req) => {
    // 将新连接的客户端添加到集合中
    clients.add(ws);
    const clientId = generateClientId();
    // 发送欢迎消息给连接的客户端
    const params = {
        type: 0,
        wel: '欢迎来到聊天室',
        userId: clientId,
    }
    ws.send(JSON.stringify(params));
    // console.log(clientId);
    // 监听消息事件
    ws.on('message', (message) => {
    // 广播消息给所有客户端
    clients.forEach((client) => {
      if (ws !== client && client.readyState === client.OPEN) {
        client.send(message);
      }
    });
  });
    // 监听连接关闭事件
    ws.on('close', () => {
        // 从集合中移除断开连接的客户端
        clients.delete(ws);
    });
});

function generateClientId() {
    return Math.random().toString(36).substr(2, 9);
  }
// 启动服务器
app.listen(3000, () => {
  console.log('Server is running');
});
